package _18_剑指OfferII;


public class _102_剑指OfferII加减的目标值 {

    public static void main(String[] args) {


        _102_剑指OfferII加减的目标值 v = new _102_剑指OfferII加减的目标值();


        int[] nums = {1, 1, 1, 1, 1};

        System.out.println(v.findTargetSumWays(nums, 3));

    }

    public int findTargetSumWays(int[] nums, int target) {
        int total = 0;
        for (int num : nums) {
            total += num;
        }
        // 组合不成功
        if (Math.abs(target) > total) return 0;
        int range = (total << 1) + 1;
        int len = nums.length;
        int[][] dp = new int[len + 1][range]; // -5
        dp[0][total] = 1;
        for (int i = 1; i <= len; ++i) {
            for (int j = 0; j < range; ++j) {
                int first = j - nums[i - 1] < 0 ? 0 : dp[i - 1][j - nums[i - 1]];
                int second = j + nums[i - 1] >= range ? 0 : dp[i - 1][j + nums[i - 1]];
                dp[i][j] += first + second;
            }
        }
        return dp[len][total + target];
    }


}
